<template>
  <div class="protocol-editor-container">
    <!-- 顶部导航栏 -->
    <div class="top-nav">
      <div class="top-nav-left">
        <el-button v-if="!editModelFlag" type="default" @click="handleBack">返回</el-button>
        <el-button v-if="editModelFlag" type="default" @click="handleCancel">取消</el-button>
        <el-button v-if="!editModelFlag" type="primary" @click="editModelFlag = true">编辑</el-button>
        <el-button v-if="editModelFlag" type="success" @click="handleSave">保存</el-button>
        <h5 style="margin-left: 20px">协议名称： </h5>
        <el-input
            v-model="protocolItem.protocolName"
            placeholder="请输入协议名称"
            :disabled="!editModelFlag"
            style="width: 300px"
        />
        <h5>所属分类： </h5>
        <el-tree-select
            :disabled="!editModelFlag"
            v-model="protocolItem.category"
            :data="treeCategories"
            :props="{ label: 'name', value: 'id', children: 'children' }"
            check-strictly=true
            placeholder="请选择分类"
            style="width: 200px"
        />
        <h5 style="margin-left: 20px">消息类型码： </h5>
        <el-input
            v-model="protocolItem.msgType"
            :disabled="!editModelFlag"
            placeholder="输入消息类型码"
            style="width: 100px"
        />
        <h5 style="margin-left: 20px">信令码： </h5>
        <el-input
            v-model="protocolItem.code"
            :disabled="!editModelFlag"
            placeholder="输入信令码"
            style="width: 100px"
        />

        <el-button v-if="modelFlag == '1' " type="warning" @click="handleImportFromOther">从已有协议导入</el-button>
      </div>
      <div class="top-nav-right">
        <el-button v-if="protocolItem.id" type="danger" @click="handleOpenProtocolParse(protocolItem.id)">解析字节流
        </el-button>
      </div>
    </div>

    <!-- 底部左右布局 -->
    <div class="bottom-container">
      <!-- 左侧：协议结构树 -->
      <div class="left-panel">
        <protocol-tree-editor
            v-model:data="protocolItem.protocolContent.fields"
            :edit-mode="editModelFlag"
        />
      </div>

      <!-- 右侧：JSON预览 -->
      <div class="right-panel">
        <h3>JSON格式预览</h3>
        <div class="json-preview">
          <pre>{{ formattedJson }}</pre>
        </div>
      </div>
    </div>

    <el-dialog v-model="showProtocolList" center width="90%">
      <ProtocolSelectList
          :show-btn="showBtn"
          @select="handleProtocolSelect"/>
    </el-dialog>
  </div>

</template>
<script lang="ts" setup>
import ProtocolTreeEditor from "@/views/ToolLibs/ProtocolViewer/components/ProtocolTreeEditor.vue";
import router from "@/router";
import {
  handleOpenProtocolParse, searchForm,
  treeCategories,
  updateCategoryList
} from "@/views/ToolLibs/ProtocolViewer/protocol";
import {getProtocolItemById, saveOrUpdateProtocolItem} from "@/api/toolLibs/protocolLib";
import {message} from "@/utils/ElmessasgeUtils";
import {computed, onMounted, ref} from "vue";
import {ElTreeSelect} from "element-plus";
import {useRoute} from "vue-router";
import type {ProtocolItemDO} from "@/type/toolLibs/protocol";
import ProtocolSelectList from "@/views/ToolLibs/ProtocolViewer/components/ProtocolSelectList.vue";

const route = useRoute()

// 0 查看模式， 1 新增模式
const modelFlag = route.query.model as string;
const protocolId = route.query.protocolId as string;
const showBtn = ref(false);

// 0:show or 1:edit
const editModelFlag = ref(modelFlag != '0');

// 协议内容
const protocolItem = ref<ProtocolItemDO>({
  id: '',
  protocolName: '',

  category: searchForm.category,

  createTime: '',
  createUserId: '',
  createUserName: '',
  createNickName: '',

  updateTime: '',
  updateUserId: '',
  updateUserName: '',
  updateNickName: '',
  protocolContent: {
    name: '',
    fields: [
      {name: "dst", type: "u8", size: 1, description: "目的进程号"},
      {name: "src", type: "u8", size: 1, description: "源进程号"},
      {name: "bodyLen", type: "u16", size: 2, description: "消息体长度"},
      {name: "msgType", type: "u8", size: 1, description: "消息类型"}
    ],
    type: ''
  }
});


const formattedJson = computed(() => {
  return JSON.stringify(protocolItem.value.protocolContent, null, 2);
})


const showProtocolList = ref(false);

async function handleImportFromOther() {
  showProtocolList.value = true;
}

function handleCancel() {

  // 查看模式
  if (modelFlag == '0') {
    editModelFlag.value = false
  }
  // 新增模式
  else {
    router.back();
  }

}

async function handleSave() {
  protocolItem.value.protocolContent.name = protocolItem.value.protocolName;
  let res = await saveOrUpdateProtocolItem(protocolItem.value)
  if (res.data.code == 200) {
    message("保存协议成功")
    protocolItem.value = res.data.data
    editModelFlag.value = false
  } else {
    message("保存协议数据失败: " + res.data.msg, 'error');
  }
}

async function updateProtocolItem() {
  let res: any = await getProtocolItemById(protocolId)
  if (res.data.code == 200) {
    protocolItem.value = res.data.data;
  } else {
    message("获取协议信息失败： " + res.data.msg, 'error');
  }

}

// 处理协议选择
async function handleProtocolSelect(selectedProtocolId: string) {
  // 关闭弹窗
  showProtocolList.value = false;

  // 获取选中协议的详情
  let res: any = await getProtocolItemById(selectedProtocolId);
  if (res.data.code == 200) {
    // 更新当前协议内容
    protocolItem.value.protocolContent = res.data.data.protocolContent;
    message("协议导入成功");
  } else {
    message("获取协议信息失败： " + res.data.msg, 'error');
  }
}

function handleBack() {
  router.back()
}

onMounted(async () => {
  await updateCategoryList();
  if (protocolId && protocolId != '') {
    await updateProtocolItem()
  }
})

</script>


<style scoped>
.protocol-editor-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 顶部导航栏样式 */
.top-nav {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px;
  background-color: #fafafa;
  border-bottom: 1px solid #e0e0e0;
  margin-bottom: 5px;
  justify-content: space-between;
}

.top-nav-left {
  display: flex;
  align-items: center;
  gap: 10px;
  background-color: #fafafa;
  border-bottom: 1px solid #e0e0e0;
  margin-bottom: 5px;
}

/* 底部左右布局 */
.bottom-container {
  display: flex;
  flex: 1;
  gap: 20px;
  padding: 0 15px 15px;
  height: calc(100% - 80px);
}

/* 左侧面板 */
.left-panel {
  flex: 1;
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 15px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.left-panel h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
}

/* 右侧面板 */
.right-panel {
  flex: 1;
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 15px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.right-panel h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
}

/* JSON预览区域 */
.json-preview {
  flex: 1;
  overflow: auto;
  background-color: #f5f7fa;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 15px;
}

.json-preview pre {
  margin: 0;
  font-family: monospace;
  font-size: 13px;
  color: #303133;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 美化滚动条 */
.json-preview::-webkit-scrollbar,
.tree::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.json-preview::-webkit-scrollbar-track,
.tree::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.json-preview::-webkit-scrollbar-thumb,
.tree::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.json-preview::-webkit-scrollbar-thumb:hover,
.tree::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
.tree > li {
  padding: 6px 0;
  border-bottom: 1px solid #f0f0f0;
}

</style>
